﻿using System;
using System.Collections.Specialized;
using System.Text;
using System.Net;
using System.IO;
using System.Configuration;
using System.Windows.Forms;

using System.ComponentModel.Composition;
using EnergyService_CSharp;

namespace TwitterPlugin
{
    [Export(typeof(IEnergyMonitorPlugin))]
    public class TwitterPlugin : IEnergyMonitorPlugin
    {
        double twInterval;
        double twEnergy = 0;
        int twReadings = 0;
        DateTime twLastTweet = DateTime.MinValue;
        oAuthTwitter _oAuth = new oAuthTwitter();

        #region IEnergyMonitorPlugin Members

        string IEnergyMonitorPlugin.Name
        {
            get { return "TwitterPlugin"; }
        }

        string IEnergyMonitorPlugin.Description
        {
            get { return "Post your energy averages to Twitter regularly."; }
        }

        bool IEnergyMonitorPlugin.Enabled
        {
            get { return bool.Parse(GetSetting("twitterplugin_enabled", "false")); }
        }

        bool IEnergyMonitorPlugin.Init()
        {
            twInterval = double.Parse(GetSetting("twitterplugin_interval", "60"));
            _oAuth.ConsumerKey = "XBdauVGJITAZerhSFsafvg";
            _oAuth.ConsumerSecret = "YaMfWB7gSgLfwFZDSQ3AZNDA5RLwMfPnmPJud7kbCzo";
            _oAuth.PIN = GetSetting("twitterplugin_pin", "");
            _oAuth.Token = GetSetting("twitterplugin_token", "");
            _oAuth.TokenSecret = GetSetting("twitterplugin_tokensecret", "");
            return true;
        }

        bool IEnergyMonitorPlugin.Notify(EnergyReading rdg)
        {
            bool retVal = false;

            twEnergy += rdg.Energy;
            twReadings++;

            if (twLastTweet.AddMinutes(twInterval) < DateTime.Now)
            {
                // it's time to tweet
                retVal= SendTweet(string.Format("In the last {0} mins {1} has used an average of {2} watts", twInterval, Environment.MachineName, (twEnergy/twReadings).ToString("N")));
                twEnergy = 0;
                twReadings = 0;
                twLastTweet = DateTime.Now;
                retVal = true;
            }

            return retVal;
        }

        bool IEnergyMonitorPlugin.DeInit()
        {
            // nothing to do in here
            return true;
        }

        NameValueCollection IEnergyMonitorPlugin.Configure(NameValueCollection current)
        {
            NameValueCollection retVal = null;

            frmConfig frm = new frmConfig(current);
            DialogResult dlg = frm.ShowDialog();

            if (DialogResult.OK == dlg)
            {
                retVal = new NameValueCollection();
                retVal.Add("twitterplugin_enabled", frm.Enabled.ToString().ToLower());
                retVal.Add("twitterplugin_interval", frm.Interval.ToString());
                if (string.Empty != frm.PIN)
                {
                    retVal.Add("twitterplugin_pin", frm.PIN);
                    retVal.Add("twitterplugin_token", frm.Token);
                    retVal.Add("twitterplugin_tokensecret", frm.TokenSecret);
                }
            }
            return retVal;
        }

        #endregion

        private bool SendTweet(string tweet)
        {
            bool retVal = false;
            try
            {
                string encTweet = System.Web.HttpUtility.UrlEncode(tweet);
                string xml = _oAuth.oAuthWebRequest(oAuthTwitter.Method.POST,"http://twitter.com/statuses/update.xml","status=" + tweet);
                retVal = true;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Error : " + ex.ToString());
            }

            return retVal;
        }

        private string GetSetting(string key, string defaultValue)
        {
            NameValueCollection appSettings = ConfigurationManager.AppSettings;
            string val = defaultValue;
            try
            {
                string v = appSettings.Get(key);
                if (null != v)
                {
                    val = v;
                }
            }
            catch
            {
                // just ignore
            }
            return val;
        }


    }
}
